import React, {useEffect, useState} from 'react';
import {Filter, Image as ImageIcon, LayoutGrid, List, Search, Tag, Trash2, Video} from 'lucide-react';
import DeleteConfirmModal from '../../components/modals/DeleteConfirmModal';
import TagManageModal from '../../components/modals/TagManageModal';
import {Req} from "../../util/fetch.ts";

interface MediaItem {
  id: number;
  type: 'image' | 'video';
  url: string;
  thumbnail?: string;
  title: string;
  event: {
    title: string;
    id: number;
  };
  size: string;
  uploadedBy: string;
  uploadedAt: string;
  tags: string[];
}

// const initialMedia: MediaItem[] = [
//   {
//     id: 1,
//     type: 'image',
//     url: 'https://images.unsplash.com/photo-1517457373958-b7bdd4587205',
//     title: '团队破冰游戏精彩瞬间',
//     event: {
//       title: '2024春雷行动-北京站',
//       id: 1
//     },
//     size: '2.5MB',
//     uploadedBy: '张经理',
//     uploadedAt: '2024-03-15 14:30',
//     tags: ['破冰游戏', '团建活动']
//   },
//   {
//     id: 2,
//     type: 'video',
//     url: 'https://example.com/video1.mp4',
//     thumbnail: 'https://images.unsplash.com/photo-1529156069898-49953e39b3ac',
//     title: '团建培训视频回顾',
//     event: {
//       title: '2024春雷行动-北京站',
//       id: 1
//     },
//     size: '15.8MB',
//     uploadedBy: '李总监',
//     uploadedAt: '2024-03-15 15:20',
//     tags: ['培训视频', '精彩回顾']
//   },
//   {
//     id: 3,
//     type: 'image',
//     url: 'https://images.unsplash.com/photo-1511578314322-379afb476865',
//     title: '团队合影留念',
//     event: {
//       title: '2024春雷行动-北京站',
//       id: 1
//     },
//     size: '3.2MB',
//     uploadedBy: '王组长',
//     uploadedAt: '2024-03-15 16:45',
//     tags: ['团队合影', '活动记录']
//   },
//   {
//     id: 4,
//     type: 'video',
//     url: 'https://example.com/video2.mp4',
//     thumbnail: 'https://images.unsplash.com/photo-1522071820081-009f0129c71c',
//     title: '破冰游戏精彩片段',
//     event: {
//       title: '520狂欢活动',
//       id: 2
//     },
//     size: '12.4MB',
//     uploadedBy: '张经理',
//     uploadedAt: '2024-03-14 10:30',
//     tags: ['破冰游戏', '精彩片段']
//   }
// ];

export default function AdminMediaLibrary() {
  const [media, setMedia] = useState<MediaItem[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [showFilters, setShowFilters] = useState(false);
  const [selectedType, setSelectedType] = useState<string>('all');
  const [selectedEvent, setSelectedEvent] = useState<string>('all');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<MediaItem | null>(null);
  const [showTagModal, setShowTagModal] = useState(false);
  const [editingMedia, setEditingMedia] = useState<MediaItem | null>(null);

  // 获取所有活动列表
  const events = Array.from(new Set(media.map(item => item.event.title)));

  const handleDelete = (item: MediaItem) => {
    setDeleteTarget(item);
    setShowDeleteModal(true);
  };

  const handleConfirmDelete = async () => {
    await Req(`/bsTrainMedia/batch?ids=${deleteTarget.id}`, {method: 'DELETE'});
    alert('删除成功')
    await queryList()
    setShowDeleteModal(false);
    setDeleteTarget(null);
  };

  const handleEditTags = (item: MediaItem) => {
    setEditingMedia(item);
    setShowTagModal(true);
  };

  const handleUpdateTags = async (newTags: string[]) => {
    const res = await Req('/bsTrainMedia/edit', {
      method: 'PUT',
      body: {
        id: editingMedia.id,
        tags: newTags.join(',')
      },
      headers: undefined
    })
    if (res.success) {
      alert(res.message)
      await queryList()
      setShowTagModal(false);
      setEditingMedia(null);
    } else {
      alert(res.message)
    }
  };

  const filteredMedia = media.filter(item => {
    const matchesSearch = 
      item.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.event.title?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.tags.some(tag => tag.toLowerCase().includes(searchTerm.toLowerCase()));
    const matchesType = selectedType === 'all' || item.type === selectedType;
    const matchesEvent = selectedEvent === 'all' || item.event.title === selectedEvent;
    return matchesSearch && matchesType && matchesEvent;
  });

  const queryList = async () => {
    const res = await Req(`/bsTrainMedia/list`)
    if (res.success) {
      setMedia(res.data.map(item => {
        return {
          id: item.id,
          type: item.fileType,
          url: item.filePath,
          thumbnail: item.thumbnail,
          title: item.fileName,
          event: {
            title: item.train ? item.train.title : '(关联训练已被删除)',
            id: item.train?.id
          },
          size: item.fileSize,
          uploadedBy: item.uploadedBy,
          uploadedAt: item.crtTime,
          tags: item.tags ? item.tags.split(',').filter(tag => tag.trim() != '') : [],
        }
      }))
    } else {
      alert(res.message)
    }
  };

  useEffect(() => {
    queryList()
  }, [])

  return (
    <div>
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-gray-900">媒体库</h1>
        <p className="text-gray-500">管理所有图片和视频资源</p>
      </div>

      {/* 工具栏 */}
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          <div className="relative w-64">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
            <input
              type="text"
              placeholder="搜索媒体..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <button
            onClick={() => setShowFilters(!showFilters)}
            className={`p-2 rounded-lg ${
              showFilters ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-600'
            }`}
          >
            <Filter className="w-5 h-5" />
          </button>
          <div className="flex items-center space-x-2 bg-gray-100 rounded-lg p-1">
            <button
              onClick={() => setViewMode('grid')}
              className={`p-2 rounded-lg ${
                viewMode === 'grid' ? 'bg-white text-blue-500 shadow-sm' : 'text-gray-600'
              }`}
            >
              <LayoutGrid className="w-5 h-5" />
            </button>
            <button
              onClick={() => setViewMode('list')}
              className={`p-2 rounded-lg ${
                viewMode === 'list' ? 'bg-white text-blue-500 shadow-sm' : 'text-gray-600'
              }`}
            >
              <List className="w-5 h-5" />
            </button>
          </div>
        </div>
        {/*<button className="flex items-center px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">*/}
        {/*  <Upload className="w-5 h-5 mr-2" />*/}
        {/*  上传文件*/}
        {/*</button>*/}
      </div>

      {/* 筛选面板 */}
      {showFilters && (
        <div className="bg-white p-4 rounded-lg shadow-sm mb-6">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">文件类型</label>
              <div className="flex space-x-4">
                <button
                  onClick={() => setSelectedType('all')}
                  className={`px-4 py-2 rounded-lg ${
                    selectedType === 'all'
                      ? 'bg-blue-500 text-white'
                      : 'bg-gray-100 text-gray-600'
                  }`}
                >
                  全部
                </button>
                <button
                  onClick={() => setSelectedType('image')}
                  className={`px-4 py-2 rounded-lg flex items-center ${
                    selectedType === 'image'
                      ? 'bg-blue-500 text-white'
                      : 'bg-gray-100 text-gray-600'
                  }`}
                >
                  <ImageIcon className="w-5 h-5 mr-2" />
                  图片
                </button>
                <button
                  onClick={() => setSelectedType('video')}
                  className={`px-4 py-2 rounded-lg flex items-center ${
                    selectedType === 'video'
                      ? 'bg-blue-500 text-white'
                      : 'bg-gray-100 text-gray-600'
                  }`}
                >
                  <Video className="w-5 h-5 mr-2" />
                  视频
                </button>
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">所属活动</label>
              <select
                value={selectedEvent}
                onChange={(e) => setSelectedEvent(e.target.value)}
                className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="all">全部活动</option>
                {events.map(event => (
                  <option key={event} value={event}>{event}</option>
                ))}
              </select>
            </div>
          </div>
        </div>
      )}

      {/* 媒体列表 */}
      {viewMode === 'grid' ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {filteredMedia.map(item => (
            <div
              key={item.id}
              className="bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-md transition-all duration-300"
            >
              <div className="relative aspect-video">
                <img
                  src={item.type === 'video' ? item.thumbnail : item.url}
                  alt={item.title}
                  className="w-full h-full object-cover"
                />
                {item.type === 'video' && (
                  <div className="absolute inset-0 flex items-center justify-center bg-black/30">
                    <Video className="w-12 h-12 text-white" />
                  </div>
                )}
              </div>
              <div className="p-4">
                <h3 className="font-medium text-gray-900 mb-1">{item.title}</h3>
                <p className="text-sm text-gray-500 mb-3">{item.event.title}</p>
                <div className="flex flex-wrap gap-2 mb-3">
                  {item.tags.map((tag, index) => (
                    <span
                      key={index}
                      className="px-2 py-1 bg-gray-100 text-gray-600 rounded-full text-xs"
                    >
                      {tag}
                    </span>
                  ))}
                </div>
                <div className="flex items-center justify-between text-sm text-gray-500">
                  <span>{item.size}</span>
                  <div className="flex items-center space-x-2">
                    <button
                      onClick={() => handleEditTags(item)}
                      className="p-1 text-gray-400 hover:text-blue-500 transition-colors"
                      title="编辑标签"
                    >
                      <Tag className="w-5 h-5" />
                    </button>
                    <button
                      onClick={() => handleDelete(item)}
                      className="p-1 text-gray-400 hover:text-red-500 transition-colors"
                      title="删除"
                    >
                      <Trash2 className="w-5 h-5" />
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="bg-white rounded-xl shadow-sm overflow-hidden">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 border-b">
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">文件</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">所属活动</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">标签</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">大小</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500">上传信息</th>
                <th className="px-6 py-4 text-right text-sm font-medium text-gray-500">操作</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {filteredMedia.map(item => (
                <tr key={item.id} className="hover:bg-gray-50">
                  <td className="px-6 py-4">
                    <div className="flex items-center">
                      <div className="w-16 h-16 rounded overflow-hidden flex-shrink-0 relative">
                        <img
                          src={item.type === 'video' ? item.thumbnail : item.url}
                          alt={item.title}
                          className="w-full h-full object-cover"
                        />
                        {item.type === 'video' && (
                          <div className="absolute inset-0 flex items-center justify-center bg-black/30">
                            <Video className="w-6 h-6 text-white" />
                          </div>
                        )}
                      </div>
                      <div className="ml-4">
                        <div className="font-medium text-gray-900">{item.title}</div>
                        <div className="text-sm text-gray-500">{item.type}</div>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4 text-gray-500">{item.event.title}</td>
                  <td className="px-6 py-4">
                    <div className="flex flex-wrap gap-2">
                      {item.tags.map((tag, index) => (
                        <span
                          key={index}
                          className="px-2 py-1 bg-gray-100 text-gray-600 rounded-full text-xs"
                        >
                          {tag}
                        </span>
                      ))}
                    </div>
                  </td>
                  <td className="px-6 py-4 text-gray-500">{item.size}</td>
                  <td className="px-6 py-4">
                    <div className="text-sm">
                      <div className="text-gray-900">{item.uploadedBy}</div>
                      <div className="text-gray-500">{item.uploadedAt}</div>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center justify-end space-x-2">
                      <button
                        onClick={() => handleEditTags(item)}
                        className="p-2 text-gray-400 hover:text-blue-500 transition-colors"
                        title="编辑标签"
                      >
                        <Tag className="w-5 h-5" />
                      </button>
                      <button
                        onClick={() => handleDelete(item)}
                        className="p-2 text-gray-400 hover:text-red-500 transition-colors"
                        title="删除"
                      >
                        <Trash2 className="w-5 h-5" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* 删除确认模态框 */}
      {showDeleteModal && deleteTarget && (
        <DeleteConfirmModal
          title="删除确认"
          message={`确定要删除"${deleteTarget.title}"吗？此操作不可恢复。`}
          onConfirm={handleConfirmDelete}
          onCancel={() => {
            setShowDeleteModal(false);
            setDeleteTarget(null);
          }}
        />
      )}

      {/* 标签管理模态框 */}
      {showTagModal && editingMedia && (
        <TagManageModal
          title={editingMedia.title}
          tags={editingMedia.tags}
          onClose={() => {
            setShowTagModal(false);
            setEditingMedia(null);
          }}
          onSave={handleUpdateTags}
        />
      )}
    </div>
  );
}